package com.mashibing.practice01.conf;

import org.apache.zookeeper.*;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * 测试zookeeper连接快速返回前需要门闩的类
 * 因为zookeeper是基于回调的响应式编程，因此下面代码在zk创建并返回时，有可能zk还没有连接上，因此创建节点就无法成功
 * 解决：我们在zk创建时基于session级别的watch中判断event的状态，如果已连接再创建节点，否则用门闩让下面的代码等待执行
 *
 * @author liuyno
 * @date 2021/3/12 - 0:08
 */
public class Tt {

    @Test
    public void testZk() {
        try {
            final CountDownLatch cd = new CountDownLatch(1);
            ZooKeeper zk = new ZooKeeper("192.168.1.10:2181,192.168.1.40:2181,192.168.1.30:2181/testConf01", 3000, new Watcher() {
                //session级别的watch
                @Override
                public void process(WatchedEvent event) {
                    System.out.println("Session Watch event : " + event.toString());
                    switch (event.getState()) {
                        case Unknown:
                            break;
                        case Disconnected:
                            break;
                        case NoSyncConnected:
                            break;
                        case SyncConnected:
                            cd.countDown();
                            System.out.println("Zk is Online!!!");
                            break;
                        case AuthFailed:
                            break;
                        case ConnectedReadOnly:
                            break;
                        case SaslAuthenticated:
                            break;
                        case Expired:
                            break;
                        case Closed:
                            break;
                    }

                    switch (event.getType()) {
                        case None:
                            break;
                        case NodeCreated:
                            break;
                        case NodeDeleted:
                            break;
                        case NodeDataChanged:
                            break;
                        case NodeChildrenChanged:
                            break;
                        case DataWatchRemoved:
                            break;
                        case ChildWatchRemoved:
                            break;
                    }
                }
            });
            cd.await();
            zk.create("/duomibaba","I love you".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            zk.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }

    }

}
